<?php

namespace app\controllers;

use App;
use app\components\ImageSerial;
use app\components\PublicHelper;
use app\components\SecurityHelper;

/**
 *
 */
class Image
{
    const SERIAL_LENGTH = 65;
    const TABLE_USER = 'tUserInfo';
    const TABLE_PDT = 'tProduct';

    public function index()
    {
        echo 'hello: ' . __METHOD__;

        // equals to :
        $list = range(1,65);

        // $list = function ($max=65)
        // {
        //     for ($i=1; $i <= $max; $i++) {
        //         yield $i;
        //     }
        // };$list()

        // shuffle($list);

        vd(APP_ENV, IN_CONSOLE, implode(',', $list));
    }

    protected function validateSignKey()
    {
    }

    /**
     * 给网站专辑图片添加水印并打包
     * @api /image/pack
     * @method POST
     * @example /image/addPackTask
     * @params [
     *     msgid
     *     opcode
     *     optime
     *     opinfo string a json string, it is contain userId,productId
     *     sign string a encrypted string
     * ]
     * @return mixed
     */
    public function addPackTask()
    {
        // 验证签名
        $params = App::input()->get();
        unset($params['sign']);

        App::logger()->info('Received message', $params);

        $rst = SecurityHelper::validate($params, App::$me->config('sign_secret'), App::input()->get('sign', ''));
        if (!$rst) {
            return App::output()->formatJson2(__LINE__, 'Signature string validation failed!');
        }

        if ( empty($params['opinfo']) ) {
            return App::output()->formatJson2(__LINE__, 'Missing parameter!');
        }

        $info = json_decode($params['opinfo'], true);
        $userId = PublicHelper::arrayGet($info, 'userId', 0);
        $productId = PublicHelper::arrayGet($info, 'productId', 0);

        if (!$userId || !$productId) {
            return App::output()->formatJson2(__LINE__, 'Missing parameter, require userId and productId!');
        }

        $table = ImageSerial::TABLE_NAME;
        $sql = "SELECT iId FROM {$table} WHERE iUserId=? AND iProductId=? LIMIT 1";
        $binds = [$userId, $productId];

        App::logger()->debug('Run SQL: '. $sql, ['binds' => $binds]);

        $stmt = App::pdo()->prepare($sql);
        $stmt->execute($binds);
        $rst = $stmt->fetch(\PDO::FETCH_ASSOC);

        // not exist, add task
        if ( !$rst ) {
            $is = new ImageSerial(App::pdo());

            if (!$status = $is->addPackTask($userId, $productId)) {
                return App::output()->formatJson2(__LINE__, 'add task failed!', [
                    'userId' => $userId,
                    'productId' => $productId
                ]);
            }
        }

        return App::output()->formatJson2(200, 'success', 1);
    }

    /**
     * 通过给定的唯一序列号生成图片序列
     * @api /image/gen-isn-by-sn
     * @params {
     *     sn string The serial number
     *     toString int (0 or 1) translate ISN to string
     * }
     * @return mixed
     */
    public function genImgSerialNumberBySN()
    {
        $sn = trim(App::input()->get('sn', ''));
        $toString = (bool)App::input()->get('toString', 1);

        if (!$sn) {
            return App::output()->formatJson(42,'Missing parameter!');
        }

        $is = new ImageSerial;

        return App::output()->formatJson([
            'SN' => $sn,
            'ISN' => $is->getISN($sn, $toString),
        ]);
    }

    /**
     * 通过给定的userId,productId生成图片序列
     * @api /image/gen-isn
     * @params {
     *     userId int
     *     productId int
     *     toString int (0 or 1) translate ISN to string
     * }
     * @return mixed
     */
    public function genImgSerialNumber()
    {
        $userId = (int)App::input()->get('userId', 0);
        $productId = (int)App::input()->get('productId', 0);
        $toString = (bool)App::input()->get('toString', 1);

        if (!$userId || !$productId) {
            return App::output()->formatJson(42,'Missing parameter!');
        }

        $sn = ImageSerial::genSerialNumber($userId, $productId);
        $is = new ImageSerial;

        return App::output()->formatJson([
            'SN' => $sn,
            'ISN' => $is->getISN($sn, $toString),
        ]);
    }

    /**
     * 根据用户id和产品id生成唯一65位序列号
     * @api /image/gen-sn
     * @example /image/gen-sn?userId=12&productId=22
     * @params {
     *     userId int
     *     productId int
     * }
     */
    public function genSerialNumber()
    {
        $userId = (int)App::input()->get('userId', 0);
        $productId = (int)App::input()->get('productId', 0);

        if (!$userId || !$productId) {
            return App::output()->formatJson(42,'Missing parameter!');
        }

        $serialNum = ImageSerial::genSerialNumber($userId, $productId);

        return App::output()->formatJson([
            'SN' => $serialNum,
        ]);
    }

    /**
     * @api /image/serial-table
     */
    public function showSerialTable()
    {
        $is = new ImageSerial;
        $table = $is->genImageNumberTable();

        if (IN_CONSOLE) {
            $content = "\n                      image serial table ";
            $content .= "\n -------------------------------------------------------- \n";
            foreach ($table as $row) {
                $content .= implode(',', $row) . "\n";
            }
            $content .= "\n End. \n";

            return App::output()->send($content);
        }

        return App::view()
            ->render('image/serial-table.php',['table' => $table])
            ->send();
    }

}
